package com.sgy.nio.buffer;

import java.nio.ByteBuffer;

/**
 * @author Administrator
 * @date 2025/8/24 16:37
 * @description 从缓冲区中读取数据
 */
public class GetBufferDemo {

    public static void main(String[] args) {
        ByteBuffer allocate = ByteBuffer.allocate(10);
        allocate.put("0123".getBytes());
        System.out.println("position:" + allocate.position());
        System.out.println("limit:" + allocate.limit());
        System.out.println("capacity:" + allocate.capacity());
        System.out.println("remaining:" + allocate.remaining());

        byte b = allocate.get();
        System.out.println("数据:" + b);

        // 切换读模式
        System.out.println("读取数据--------------------");
        allocate.flip();
        for (int i = 0; i < allocate.limit(); i++) {
            System.out.println(allocate.get());
        }

        // 读取指定索引字节
        System.out.println("读取指定索引字节--------------------");
        System.out.println(allocate.get(1));

        // 读取多个字节
        System.out.println("读取多个字节--------------------");
        allocate.rewind();  // 重复读取，将position置为0
        byte[] bytes = new byte[4];
        allocate.get(bytes);
        System.out.println(new String(bytes));

        // 将缓冲区转换为字节数组返回
        System.out.println("将缓冲区转换为字节数组返回--------------------");
        byte[] array = allocate.array();
        System.out.println(new String(array));

        // 切换写模式
        System.out.println("切换写模式--------------------");
        allocate.clear();
        allocate.put("abc".getBytes());
        System.out.println(new String(array));
    }
}
